<template>
  <a-layout>
    <a-layout-content class="content-layout">
      <a-card title="用户设置" class="user-setting-card" bordered={false}>
        <!-- 头像上传区域 -->
        <a-row gutter={16} justify="center" class="avatar-upload-row">
          <a-col :span="8" class="avatar-col">
            <a-form-item style="margin-bottom: 0;">
              <a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card" class="avatar-uploader"
                :show-upload-list="false" :action="uploadAction" :before-upload="beforeUpload" @change="handleChange"
                :on-success="handleSuccess">
                <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="avatar-image" />
                <div v-else>
                  <a-icon v-if="loading" type="loading" />
                  <a-icon v-else type="plus" />
                  <div class="ant-upload-text">上传头像</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 用户基本信息 -->
        <a-row gutter={16} class="info-row">
          <a-col :span="11">
            <a-form-item label="用户名" style="margin-bottom: 10px;">
              <a-text>{{ user.username }}</a-text>
            </a-form-item>
          </a-col>
          <a-col :span="11" offset="2">
            <a-form-item label="邮箱" style="margin-bottom: 10px;">
              <a-text>{{ user.email }}</a-text>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row gutter={16} class="info-row">
          <a-col :span="11">
            <a-form-item label="性别" style="margin-bottom: 10px;">
              <a-text>
                {{ user.gender === '0' ? '男' : (user.gender === '1' ? '女' : (user.gender === '2' ? '其他' : '')) }}
              </a-text>
            </a-form-item>
          </a-col>
          <a-col :span="11" offset="2" v-if="user.createdAt">
            <a-form-item label="加入日期" style="margin-bottom: 10px;">
              <a-text>{{ user.createdAt }}</a-text>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 修改密码的行 -->
        <a-row gutter={16} class="info-row">
          <a-col :span="8">
            <a-form-item label="">
              <a-input v-model:value="user.newPassword" placeholder="修改密码需要验证" type="password" size="large" />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 验证码的行 -->
        <a-row gutter={16} class="info-row">
          <a-col :span="5">
            <a-input v-model:value="code" placeholder="请输入验证码" size="large" />
          </a-col>
          <a-col :span="1" offset="0" style="display: flex; align-items: center;margin-left: 5px;">
            <a-form-item label="">
              <a-button @click="sendCode" :disabled="isSendingCode" size="large">
                {{ isSendingCode ? '发送中...' : '获取验证码' }}
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 提交按钮 -->
        <a-row justify="center" style="margin-top: 24px;">
          <a-col :span="8">
            <a-button type="primary" @click="updateUserInfo" size="large" block>
              保存
            </a-button>
          </a-col>
        </a-row>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import { getUserInfoApi } from '@/api/user';
import { codeSend, userUpdate } from '@/api/user';
import { notification } from 'ant-design-vue'; // 导入通知组件
// 存储用户信息
const user = ref({
  username: '',
  email: '',
  profilePictureUrl: '',
  phoneNumber: '',
  gender: null,
  createdAt: null,
  address: '',
  newPassword: '',
});

// 存储头像上传相关信息
const fileList = ref([]);
const imageUrl = ref(null); // 存储头像图片的URL
const loading = ref(false); // 控制上传时的loading效果
const code = ref(''); // 验证码
const isSendingCode = ref(false); // 控制验证码按钮状态
const uploadAction = '/api/file/fileUpload';

// 页面加载时查询用户信息
const getUserInfo = async () => {
  try {
    const res = await getUserInfoApi();
    if (res.code === 200) {
      const userInfo = res.data;
      user.value.username = userInfo.username;
      user.value.email = userInfo.email || '';
      user.value.gender = userInfo.gender;
      user.value.createdAt = userInfo.createdAt || '';
      user.value.address = userInfo.address || '';
      user.value.profilePictureUrl = userInfo.profilePictureUrl;
      imageUrl.value = userInfo.profilePictureUrl || 'default-avatar.png';
      user.value.phoneNumber = userInfo.phoneNumber;
    } else {
      message.error('获取用户信息失败');
    }
  } catch (error) {
    message.error('获取用户信息失败');
  }
};

// 上传前处理
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
  }
  return isImage;
};

// 头像上传成功后的回调
const handleSuccess = (response, file) => {
  imageUrl.value = response.data || file.thumbUrl;
};

// 头像上传后处理
const handleChange = ({ fileList: newFileList }) => {
  fileList.value = newFileList;
  if (newFileList.length > 0 && newFileList[0].status === 'done') {
    imageUrl.value = newFileList[0].response?.url || newFileList[0].thumbUrl;
  }
};

// 发送验证码
const sendCode = async () => {
  if (!user.value.phoneNumber) {
    message.error('没有找到用户手机号');
    return;
  }

  isSendingCode.value = true;
  try {
    const response = await codeSend(user.value.phoneNumber);
    if (response.code == 200) {
      notification.info({
            message: '验证码已发送',
            description: '没钱！ 验证码 = ' + response.data
            // description: '验证码已发送到您的手机!',
        });
    } else {
      message.error('发送验证码失败');
    }
  } catch (error) {
    message.error('发送验证码失败');
  } finally {
    isSendingCode.value = false;
  }
};

// 提交更新
const updateUserInfo = async () => {
  try {
    const response = await userUpdate({
      phoneNumber: user.value.phoneNumber,
      profilePictureUrl: imageUrl.value,
      password: user.value.newPassword, // 修改的新密码
      code: code.value, // 用户输入的验证码
    });
    if (response.code == 200) {
      message.success('信息更新成功!');
    } else {
      message.error('信息更新失败!');
    }
  } catch (error) {
    message.error('信息更新失败!');
  }
};

// 页面加载时获取用户信息
onMounted(async () => {
  getUserInfo();
});
</script>

<style scoped>
.content-layout {
  padding: 20px;
  background-color: #f5f5f5;
}

.user-setting-card {
  width: 100%;
  margin: 0 auto;
  padding: 24px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.avatar-upload-row {
  margin-bottom: 16px;
  text-align: center;
}

.avatar-col {
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.ant-upload-text {
  margin-top: 8px;
  font-size: 14px;
}

.info-row {
  margin-bottom: 12px;
}

a-input,
a-select,
a-date-picker {
  font-size: 14px;
  height: 36px;
  border-radius: 8px;
}

a-button {
  font-size: 16px;
  border-radius: 8px;
}

a-button:hover {
  opacity: 0.9;
}

.form-item label {
  font-weight: bold;
  font-size: 14px;
  color: #333;
}
</style>
